package net.mihome.app.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMContactManager;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.activity.ChatActivity;
import com.easemob.chatuidemo.activity.GroupSimpleDetailActivity;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.adapter.FriendGroupAdapter;
import net.mihome.app.bean.Group;
import net.mihome.app.bean.MyInformation;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.ui.view.MihomeBigPaperView;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 用户资料
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class FriendInfo extends BaseActivity {

    private ProgressDialog progressDialog;
    private View hisDazibaoViewBtn;
    private View hisDazibaoContentView;
    private ListView quanziListview;
    private FriendGroupAdapter quanziAdapter;
    private List<Group> groupList=new ArrayList<>();
    private View hisQuanziViewBtn;
    private View hisQuanziContentView;
    private MihomeBigPaperView mihomeBigPaperView;
    private ListView hisQuanziListview;
    private Integer friendId;
    private String openId;
    private boolean isMyFriend;
    private User friendUser;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_info);
        //获取用户信息
        friendId=getIntent().getIntExtra("uid",-1);
        openId=getIntent().getStringExtra("open_id");
        if((friendId==null||friendId==-1)&&openId==null){
            Toast.makeText(this,"无法获取到用户信息",Toast.LENGTH_SHORT).show();
            this.finish();
        }
        quanziListview= (ListView) findViewById(R.id.his_quanzi_listview);
        quanziAdapter=new FriendGroupAdapter(this,groupList);
        quanziListview.setAdapter(quanziAdapter);
        loadUserInfoThread();
        //
        mihomeBigPaperView= (MihomeBigPaperView) findViewById(R.id.his_dazibao_listview);
        hisQuanziListview= (ListView) findViewById(R.id.his_quanzi_listview);
        //添加展开和关闭事件
        hisDazibaoViewBtn=findViewById(R.id.friend_liearlayout_hisdazibao_btn);
        hisDazibaoContentView=findViewById(R.id.his_dazibao_content_view);
        hisDazibaoViewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(hisDazibaoContentView.getVisibility()==View.GONE){
                    loadDazibao();
                    hisDazibaoContentView.setVisibility(View.VISIBLE);
                    ((ImageView)hisDazibaoViewBtn.findViewById(R.id.btn_icon)).setImageResource(R.drawable.point_to_bottm);
                    //展开第一个，将第二个合上
                    hisQuanziContentView.setVisibility(View.GONE);
                    ((ImageView)hisQuanziViewBtn.findViewById(R.id.btn_icon2)).setImageResource(R.drawable.point_to_top);
                }else{
                    hisDazibaoContentView.setVisibility(View.GONE);
                    ((ImageView)hisDazibaoViewBtn.findViewById(R.id.btn_icon)).setImageResource(R.drawable.point_to_top);
                }
            }
        });
        hisQuanziViewBtn=findViewById(R.id.friend_liearlayout_hisquanzi_btn);
        hisQuanziContentView=findViewById(R.id.his_quanzi_content_view);
        hisQuanziViewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(hisQuanziContentView.getVisibility()==View.GONE){
                    loadGroups();
                    hisQuanziContentView.setVisibility(View.VISIBLE);
                    ((ImageView)hisQuanziViewBtn.findViewById(R.id.btn_icon2)).setImageResource(R.drawable.point_to_bottm);
                }else{
                    hisQuanziContentView.setVisibility(View.GONE);
                    ((ImageView)hisQuanziViewBtn.findViewById(R.id.btn_icon2)).setImageResource(R.drawable.point_to_top);
                }
            }
        });
        quanziListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                startActivity(new Intent(FriendInfo.this, GroupSimpleDetailActivity.class).putExtra("groupinfo_my", (Group) quanziAdapter.getItem(i)));
            }
        });
	}
    /**
     * 加载大字报
     * */
    public void loadDazibao(){
        if(friendUser==null){
            Toast.makeText(this,"无法获取到该用户信息",Toast.LENGTH_SHORT).show();
        }else{
            this.mihomeBigPaperView.initData(friendUser.getUid());
        }
    }
    /**
     * 初始化用户信息
     * */
    private void loadUserInfoThread() {
        RequestParams requestParams = RequestParamsFactory.newInstance(AppContext.getInstance());
        if (friendId != null && friendId != -1) {
            requestParams.add("to_uid", friendId.toString());
        }else if (openId != null) {
            requestParams.add("to_open_id", openId);
        }
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_FRIEND_INFO_MARK, requestParams, new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                User user = User.parse(responsePojo.getData());
                friendUser=user;
                if(user.getFace()!=null&&!"".equals(user.getFace())){
                    ImageLoader.getInstance().displayImage(user.getFace(), (ImageView) FriendInfo.this.findViewById(R.id.friend_info_userface));
                }else {
                    ((ImageView)FriendInfo.this.findViewById(R.id.friend_info_userface)).setImageResource(R.drawable.widget_dface);
                }
                if(user.getRealName()!=null&&!"".equals(user.getRealName())){
                    ((TextView)FriendInfo.this.findViewById(R.id.friend_info_username)).setText(user.getRealName());
                }else{
                    ((TextView)FriendInfo.this.findViewById(R.id.friend_info_username)).setText(user.getName());
                }
                if(user.getCommunity().getName()!=null){
                    ((TextView)FriendInfo.this.findViewById(R.id.friend_info_build)).setText(user.getCommunity().getName());
                }
                if(checkIsFriend(user.getOpenId())){
                    isMyFriend=true;
                    ((Button)FriendInfo.this.findViewById(R.id.btn_text)).setText("发送消息");
                    findViewById(R.id.friend_info_mark_tip).setVisibility(View.VISIBLE);
                    findViewById(R.id.friend_info_mark_content).setVisibility(View.VISIBLE);
                }else{
                    isMyFriend=false;
                    ((Button)FriendInfo.this.findViewById(R.id.btn_text)).setText("加为邻居");
                }
                if(user.getMarkName()!=null&&!"".equals(user.getMarkName())){
                    ((TextView)FriendInfo.this.findViewById(R.id.mark_name)).setText(user.getMarkName());
                }
                if(user.getMarkAddress()!=null&&!"".equals(user.getMarkAddress())){
                    ((TextView)FriendInfo.this.findViewById(R.id.mark_address)).setText(user.getMarkAddress());
                }
                if(user.getMarkEmail()!=null&&!"".equals(user.getMarkEmail())){
                    ((TextView)FriendInfo.this.findViewById(R.id.mark_email)).setText(user.getMarkEmail());
                }
                if(user.getMarkPhoneNum()!=null&&!"".equals(user.getMarkPhoneNum())){
                    ((TextView)FriendInfo.this.findViewById(R.id.mark_phone_num)).setText(user.getMarkPhoneNum());
                }
                if(user.getMarkQq()!=null&&!"".equals(user.getMarkQq())){
                    ((TextView)FriendInfo.this.findViewById(R.id.mark_qq)).setText(user.getMarkQq());
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(FriendInfo.this, arg3.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void back(View view){
        finish();
    }
    /**
     * 点击底部按钮操作
     * */
    public void btnEvent(View view){
        if(isMyFriend){
            Intent intent=new Intent(FriendInfo.this, ChatActivity.class).putExtra("userId",friendUser.getOpenId());
            intent.putExtra("userName",friendUser.getRealName());
            startActivity(intent);
        }else{
            if(friendUser.getOpenId()==null){
                Toast.makeText(this,"请提供用户信息",Toast.LENGTH_SHORT).show();
                return ;
            }
            String curOpenId=AppContext.getInstance().getLoginInfo().getOpenId();
            if(curOpenId.equals(friendUser.getOpenId())){
                startActivity(new Intent(this, com.easemob.chatuidemo.activity.AlertDialog.class).putExtra("msg", "不能添加自己"));
                return;
            }

            if(checkIsFriend(friendUser.getOpenId())){
                startActivity(new Intent(this, com.easemob.chatuidemo.activity.AlertDialog.class).putExtra("msg", "此用户已是你的好友"));
                return;
            }
            showAddMsg(friendUser);
        }
    }
    /**
     * 通过该用户的openId，判断该用户是否是自己的好友
     * */
    public boolean checkIsFriend(String openId){
        Map<String,User> users=AppContext.getInstance().getContactList();
        if(users==null){
            return false;
        }
        Iterator<Map.Entry<String, User>> iterator=users.entrySet().iterator();
        {
            while(iterator.hasNext()){
                Map.Entry<String,User> entry=iterator.next();
                if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME)&& !entry.getKey().equals(Constant.ADD_CONTRACT))
                {
                    User user=entry.getValue();
                    if(user==null||user.getOpenId()==null){
                        continue;
                    }
                    if(user.getOpenId().equals(openId)){
                        return true;
                    }
                }
            }
        }
        return false;
    }
    /**
     * 加载群组列表
     * */
    public void loadGroups(){
        if(friendUser==null){
            Toast.makeText(this,"无法获取到该用户信息",Toast.LENGTH_SHORT).show();
            return ;
        }
        if(groupList!=null&&groupList.size()>0){
            return ;
        }
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("want_uid",friendUser.getUid());
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_USER_CHAT_GET_GROUP_LIST,requestParams,new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<Group> list=Group.parseList(responsePojo.getData());
                if(list!=null){
                    groupList.clear();
                    groupList.addAll(list);
                }
                quanziAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(FriendInfo.this,"无法获取到该用户信息",Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void saveMark(View view){
        String markName=((EditText)findViewById(R.id.mark_name)).getText().toString();
        String markPhoenNum=((EditText)findViewById(R.id.mark_phone_num)).getText().toString();
        String markAddress=((EditText)findViewById(R.id.mark_address)).getText().toString();
        String markEmail=((EditText)findViewById(R.id.mark_email)).getText().toString();
        String markQq=((EditText)findViewById(R.id.mark_qq)).getText().toString();
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("to_uid",friendUser.getUid());
        requestParams.put("name",markName);
        requestParams.put("address",markAddress);
        requestParams.put("email",markEmail);
        requestParams.put("phone_num",markPhoenNum);
        requestParams.put("qq",markQq);
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_USER_CHAT_SAVE_MARK,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                Toast.makeText(FriendInfo.this,"保存成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(FriendInfo.this,"保存失败"+arg3.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 添加好友
     * */
    /**
     * 显示一个对话框，让用户填写好友验证
     * */
    public void showAddMsg(final User user){
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.add_contact_dialog, null);//这里的
        final EditText editText= (EditText) view.findViewById(R.id.add_contact_msg);
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle("请输入验证信息:");
        builder.setMessage("你想对他(她)说点什么?");
        builder.setView(view);
        builder.setPositiveButton(R.string.text_queding, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(FriendInfo.this,"确定",Toast.LENGTH_SHORT).show();
                dialogInterface.dismiss();

                addContact(user,editText.getText().toString());
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.create().show();
    }
    /**
     * 启动线程添加好友
     * */
    public void addContact(final User user,final String msg){
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在发送请求...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {
                try {
                    //demo写死了个reason，实际应该让用户手动填入
                    EMContactManager.getInstance().addContact(user.getOpenId(), "验证信息:"+msg);
                    FriendInfo.this.runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(FriendInfo.this, "发送请求成功,等待对方验证", Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (final Exception e) {
                    FriendInfo.this.runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(FriendInfo.this, "请求添加好友失败:" + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }
 }
